import json
import shutil
from datetime import datetime

def load_annotation_file(file_path):
    """加载标注文件"""
    with open(file_path, 'r', encoding='utf-8') as f:
        return json.load(f)

def save_annotation_file(data, file_path):
    """保存标注文件"""
    with open(file_path, 'w', encoding='utf-8') as f:
        json.dump(data, f, ensure_ascii=False, indent=2)

def fix_bbox_order(annotation_data):
    """修复bbox点顺序
    
    将顺时针顺序：p1(右上) -> p2(左上) -> p3(左下) -> p4(右下)
    转换为逆时针顺序：p1(左上) -> p2(右上) -> p3(右下) -> p4(左下)
    """
    print("开始修复bbox点顺序...")
    
    fixed_cells = 0
    for cell in annotation_data['cells']:
        if cell['bbox']:
            # 获取原始点
            original_bbox = cell['bbox'].copy()
            p1_orig = original_bbox['p1']  # 原来的右上角
            p2_orig = original_bbox['p2']  # 原来的左上角  
            p3_orig = original_bbox['p3']  # 原来的左下角
            p4_orig = original_bbox['p4']  # 原来的右下角
            
            # 重新分配点位置，转换为标准的逆时针顺序
            cell['bbox']['p1'] = p2_orig  # 左上角
            cell['bbox']['p2'] = p1_orig  # 右上角
            cell['bbox']['p3'] = p4_orig  # 右下角
            cell['bbox']['p4'] = p3_orig  # 左下角
            
            fixed_cells += 1
            
            print(f"修复单元格 {cell['cell_ind']}:")
            print(f"  原始: p1(右上){p1_orig} p2(左上){p2_orig} p3(左下){p3_orig} p4(右下){p4_orig}")
            print(f"  修复: p1(左上){cell['bbox']['p1']} p2(右上){cell['bbox']['p2']} p3(右下){cell['bbox']['p3']} p4(左下){cell['bbox']['p4']}")
    
    # 更新质量状态
    annotation_data['quality'] = "已修复"
    
    print(f"\n修复完成！共修复了 {fixed_cells} 个单元格的bbox点顺序")
    return annotation_data

def verify_fix(annotation_data):
    """验证修复结果"""
    print("\n验证修复结果...")
    
    def get_corner_position(point, all_points):
        """确定点在矩形中的位置"""
        x_coords = [p[0] for p in all_points]
        y_coords = [p[1] for p in all_points]
        
        min_x, max_x = min(x_coords), max(x_coords)
        min_y, max_y = min(y_coords), max(y_coords)
        
        x, y = point
        if abs(x - min_x) < abs(x - max_x):  # 更接近左边
            if abs(y - min_y) < abs(y - max_y):  # 更接近上边
                return "左上角"
            else:  # 更接近下边
                return "左下角"
        else:  # 更接近右边
            if abs(y - min_y) < abs(y - max_y):  # 更接近上边
                return "右上角"
            else:  # 更接近下边
                return "右下角"
    
    correct_count = 0
    total_count = 0
    
    for cell in annotation_data['cells']:
        if cell['bbox']:
            bbox = cell['bbox']
            p1, p2, p3, p4 = bbox['p1'], bbox['p2'], bbox['p3'], bbox['p4']
            all_points = [p1, p2, p3, p4]
            
            # 检查每个点是否在正确位置
            p1_pos = get_corner_position(p1, all_points)  # 应该是左上角
            p2_pos = get_corner_position(p2, all_points)  # 应该是右上角
            p3_pos = get_corner_position(p3, all_points)  # 应该是右下角
            p4_pos = get_corner_position(p4, all_points)  # 应该是左下角
            
            is_correct = (p1_pos == "左上角" and p2_pos == "右上角" and 
                         p3_pos == "右下角" and p4_pos == "左下角")
            
            if is_correct:
                correct_count += 1
            else:
                print(f"单元格 {cell['cell_ind']} 仍有问题: p1({p1_pos}) p2({p2_pos}) p3({p3_pos}) p4({p4_pos})")
            
            total_count += 1
    
    success_rate = (correct_count / total_count) * 100 if total_count > 0 else 0
    print(f"\n验证结果: {correct_count}/{total_count} 个单元格正确 ({success_rate:.1f}%)")
    
    return success_rate == 100.0

def main():
    # 文件路径
    input_file = "1617292400882827329823143747584_0_table_annotation.json"
    backup_file = f"{input_file}.backup_{datetime.now().strftime('%Y%m%d_%H%M%S')}"
    output_file = f"fixed_{input_file}"
    
    print("="*60)
    print("表格标注文件bbox点顺序修复工具")
    print("="*60)
    
    # 创建备份
    print(f"创建备份文件: {backup_file}")
    shutil.copy2(input_file, backup_file)
    
    # 加载原始文件
    print(f"加载原始文件: {input_file}")
    annotation_data = load_annotation_file(input_file)
    
    print(f"原始文件信息:")
    print(f"  表格类型: {annotation_data.get('type', 'Unknown')}")
    print(f"  质量状态: {annotation_data.get('quality', 'Unknown')}")
    print(f"  单元格数量: {len(annotation_data['cells'])}")
    
    # 修复bbox点顺序
    fixed_data = fix_bbox_order(annotation_data)
    
    # 验证修复结果
    if verify_fix(fixed_data):
        print("✅ 修复验证通过！")
    else:
        print("❌ 修复验证失败，请检查！")
    
    # 保存修复后的文件
    print(f"\n保存修复后的文件: {output_file}")
    save_annotation_file(fixed_data, output_file)
    
    print("\n修复完成！")
    print(f"原始文件备份: {backup_file}")
    print(f"修复后文件: {output_file}")
    print("\n建议:")
    print("1. 检查修复后的文件是否符合预期")
    print("2. 如果满意，可以用修复后的文件替换原始文件")
    print("3. 如果有问题，可以从备份文件恢复")

if __name__ == "__main__":
    main()
